/*
*  Copyright 2019-2023 oyun
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/package com.oyun.modules.document.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oyun.modules.document.domain.BookDictionary;
import com.oyun.modules.document.domain.BookDocuments;
import com.oyun.modules.document.domain.DocPicture;
import com.oyun.modules.document.domain.vo.BookDocumentsQueryCriteria;
import com.oyun.modules.document.mapper.BookDocumentsMapper;
import com.oyun.modules.document.mapper.DocPictureMapper;
import com.oyun.modules.document.service.BookDocumentsService;
import com.oyun.modules.medicine.domain.DoctorPicture;
import com.oyun.segment.convert.itmd.IntermediateCodeUtils;
import com.oyun.utils.FileUtil;
import com.oyun.utils.PageResult;
import com.oyun.utils.PageUtil;
import com.oyun.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
* @description 服务实现
* @author oyun
* @date 2024-05-11
**/
@Service
@RequiredArgsConstructor
public class BookDocumentsServiceImpl extends ServiceImpl<BookDocumentsMapper, BookDocuments> implements BookDocumentsService {

    private final BookDocumentsMapper bookDocumentsMapper;

    @Value("${file.windows.path}")
    private String path;

    private final DocPictureMapper docPictureMapper;

    @Override
    public PageResult<BookDocuments> queryAll(BookDocumentsQueryCriteria criteria, Page<Object> page){
        if (StringUtils.isNotEmpty(criteria.getName())) {
            criteria.setReplaceAll(IntermediateCodeUtils.mn2Code(criteria.getName()).replaceAll("-", " -"));
        }
        return PageUtil.toPage(bookDocumentsMapper.findAll(criteria, page));
    }

    @Override
    public List<BookDocuments> queryAll(BookDocumentsQueryCriteria criteria){
        return bookDocumentsMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(BookDocuments resources) {
        convertCode(resources);
        save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(BookDocuments resources) {
        BookDocuments bookDocuments = getById(resources.getId());
        bookDocuments.copy(resources);
        convertCode(bookDocuments);
        saveOrUpdate(bookDocuments);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Long> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<BookDocuments> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (BookDocuments bookDocuments : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put(" isbn",  bookDocuments.getIsbn());
            map.put("分类id", bookDocuments.getClassificationId());
            map.put("内容语言id", bookDocuments.getDictionaryId());
            map.put(" mnName",  bookDocuments.getMnName());
            map.put(" nameCode",  bookDocuments.getNameCode());
            map.put(" zhName",  bookDocuments.getZhName());
            map.put("拉丁撰写题名", bookDocuments.getLdName());
            map.put("作者", bookDocuments.getAuthor());
            map.put("出版者", bookDocuments.getPublisher());
            map.put("出版地", bookDocuments.getPlacePublication());
            map.put("印刷者", bookDocuments.getPrinter());
            map.put("来源", bookDocuments.getSource());
            map.put("开本", bookDocuments.getFormat());
            map.put("简介", bookDocuments.getIntro());
            map.put(" createBy",  bookDocuments.getCreateBy());
            map.put(" createTime",  bookDocuments.getCreateTime());
            map.put(" updateBy",  bookDocuments.getUpdateBy());
            map.put(" updateTime",  bookDocuments.getUpdateTime());
            map.put(" remark",  bookDocuments.getRemark());
            map.put(" status",  bookDocuments.getStatus());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public String uploadOrUpdate(MultipartFile file, HttpServletRequest request, Long id) {
        File filee = new File(path+"/document");
        if(!filee.exists()){//不存在
            filee.mkdirs();
        }
//        String filename = file.getOriginalFilename();//获取文件名称带后缀名
//        String uid = UUID.randomUUID().toString();//生成32为uuid值
//        String suffix = filename.substring(filename.lastIndexOf(".")); //切割获取.后面的jpg
//        String newFile = uid + suffix;//拼接新的文件名称
        File file1 = new File(filee+ "/" + file.getOriginalFilename());
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String originalFilename = file.getOriginalFilename();
        //新增或修改
        LambdaQueryWrapper<DocPicture> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(id != null,DocPicture::getDocId,id).eq(DocPicture::getStatus,1).eq(DocPicture::getFilename,originalFilename);
        DocPicture docPicture1 = docPictureMapper.selectOne(wrapper);
        if (docPicture1 == null){
            DocPicture docPicture = new DocPicture();
            docPicture.setDocId(id);
            docPicture.setPath("/document/"+file.getOriginalFilename()); //newFile
            docPicture.setFilename(file.getOriginalFilename()); //newFile
            docPicture.setStatus(1);
            docPictureMapper.insert(docPicture);
        }else {
            docPicture1.setPath("/document/"+file.getOriginalFilename());//newFile
            docPicture1.setStatus(1);
            docPictureMapper.updateById(docPicture1);
        }
        return file.getOriginalFilename();//newFile
    }


    private void convertCode(BookDocuments bookDocuments) {
        bookDocuments.setNameCode(IntermediateCodeUtils.mn2Code(bookDocuments.getMnName()).replaceAll("-", " -"));
    }
}
